package com.pospi.pospihold.print.a920;

import android.graphics.Bitmap;
import android.util.Log;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.util.Hashtable;

public class QrUtils {

	private static final String TAG = QrUtils.class.getSimpleName();
	private static final int PADDING_SIZE_MIN = 0; // 最小留白长度, 单位: px
	/*
	 * 条形码
	 */
	public static Bitmap creatBarCode(String contents, int width, int height) {

		try {
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

			// 图像数据转换，使用了矩阵转换
			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.CODE_128, width, height, hints);
			Bitmap bitmap = toBitmap(bitMatrix);

			return bitmap;
		} catch (Exception e) {
			Log.w(TAG, e.toString());
		}

		return null;
	}

	private static Bitmap toBitmap(BitMatrix byteMatrix) {

		// 定义位图的宽和高
		int width = byteMatrix.getWidth();
		int height = byteMatrix.getHeight();
		int[] pixels = new int[width * height];

		boolean isFirstBlackPoint = false;
		int startX = 0;
		int startY = 0;
		// 下面这里按照二维码的算法，逐个生成二维码的图片， 两个for循环是图片横列扫描的结果
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (byteMatrix.get(x, y)) {
					if (isFirstBlackPoint == false) {
					isFirstBlackPoint = true;
					startX = x;
					startY = y;
					}
					pixels[y * width + x] = 0xff000000;
				} else {
					pixels[y * width + x] = 0xffffffff;
				}
			}
		}
		// 生成二维码图片的格式，使用ARGB_8888
		Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap,具体参考api
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		//去除bitmap的白色边框
		if (startX <= PADDING_SIZE_MIN)
			return bitmap;

		int x1 = startX - PADDING_SIZE_MIN;
		int y1 = startY - PADDING_SIZE_MIN;
		if (x1 < 0 || y1 < 0)
			return bitmap;

		int w1 = width - x1 * 2;
		int h1 = height - y1 * 2;

		Bitmap bitmapQR = Bitmap.createBitmap(bitmap, x1, y1, w1, h1);
		return bitmapQR;
	}

	/*
	 * 二维码
	 */
	public static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException {
		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, hints);
		return toBitmap(matrix);
	}

}
